/*
** voir.c for zappy in /home/guidet_m/TECK2/projets/zappy/server_zappy
** 
** Made by michael guidet
** Login   <guidet_m@epitech.net>
** 
** Started on  Mon Jul  4 15:33:32 2011 michael guidet
** Last update Mon Jul 11 10:14:38 2011 michael guidet
*/

#include "server.h"

void		action_voir_init(t_fd *fd, char **cmd2, int *len, char *cmd)
{
  printf("%sDrone %d %s Execute %s%s\n", PURPLE, fd->pl->id,
	 fd->pl->team, cmd, DEFAUT);
  fd->wait = -1;
  fd->idaction = -1;
  (*len) = BUF_SIZE;
  (*cmd2) = x_null(NULL, malloc(sizeof((**cmd2)) * ((*len) + 1)), "malloc");
  memset((*cmd2), 0, BUF_SIZE + 1);
  (*cmd2)[0] = '{';
}

void		voir_contenu(t_env *e, t_coord deb, char **cmd2, int *len)
{
  t_player_list	*tmp;
  int		i;
  int		j;

  for (tmp = e->map[deb.y][deb.x].players; tmp; tmp = tmp->next)
    xstrcat(cmd2, " joueur", len);
  for (i = 0; i < ALL_RC; i++)
    for (j = 0; j < e->map[deb.y][deb.x].ressource[i]; j++)
      {
	if (i == NOURRITURE)
	  xstrcat(cmd2, " nourriture", len);
	else if (i == LINEMATE)
	  xstrcat(cmd2, " linemate", len);
	else if (i == DERAUMERE)
	  xstrcat(cmd2, " deraumere", len);
	else if (i == SIBUR)
	  xstrcat(cmd2, " sibur", len);
	else if (i == MENDIANE)
	  xstrcat(cmd2, " mendiane", len);
	else if (i == PHIRAS)
	  xstrcat(cmd2, " phiras", len);
	else if (i == THYSTAME)
	  xstrcat(cmd2, " thystame", len);
      }
}

void		action_voir_relative(t_coord *deb, t_env *e)
{
  if (deb->x >= e->width)
    deb->x -= e->width;
  else if (deb->x < 0)
    deb->x = e->width + deb->x;
  if (deb->y >= e->height)
    deb->y -= e->height;
  else if (deb->y < 0)
    deb->y = e->height + deb->y;
}

void		action_voir_pos(t_coord *deb, int i, int j, t_fd *fd)
{
  if (fd->pl->look_at == OUEST)
    {
      deb->x -= i;
      deb->y -= j;
    }
  else if (fd->pl->look_at == NORD)
    {
      deb->x -= j;
      deb->y -= i;
    }
  else if (fd->pl->look_at == SUD)
    {
      deb->x += j;
      deb->y += i;
    }
  else
    {
      deb->x += i;
      deb->y += j;
    }
}

void		action_voir(t_fd *fd, t_env *e, char *cmd)
{
  int		len;
  char		*cmd2;
  t_coord	deb;
  int		i;
  int		j;

  action_voir_init(fd, &cmd2, &len, cmd);
  for (i = 0; i <= fd->pl->level; i++)
    {
      for (j = -i; j <= i; j++)
	{
	  deb.x = fd->pl->x;
	  deb.y = fd->pl->y;
	  action_voir_pos(&deb, i, j, fd);
	  action_voir_relative(&deb, e);
	  voir_contenu(e, deb, &cmd2, &len);
	  if (i != fd->pl->level || (j != i && i == fd->pl->level))
	    xstrcat(&cmd2, ",", &len);
	}
    }
  xstrcat(&cmd2, "}\n", &len);
  add_string_to_list(&fd->send_list, cmd2);
  free(cmd2);
}
